<template>
  <div class="progress-list">
    <div
      v-for="(item, index) in dataList"
      :key="item.time"
      class="progress-list-item"
    >
      <div
        class="progress-list-time"
        :class="{ active: expandedIndices.includes(index) }"
      >
        <div @click="toggle(index)">
          <i
            :class="[
              'el-icon',
              expandedIndices.includes(index)
                ? 'el-icon-arrow-down'
                : 'el-icon-arrow-right'
            ]"
            :style="{
              color: expandedIndices.includes(index)
                ? '#1890ff'
                : '#606266'
            }"
          ></i>
          <span class="time-text">{{
            item.createTime || item.updateTime
          }}</span>
        </div>
        <div>
          <span
            class="edit"
            @click="editProcess(item, index)"
            v-if="!isDetail"
          >
            编辑
          </span>
          <span
            class="delete"
            @click="deleteProcess(index)"
            v-if="!isDetail"
          >
            删除
          </span>
        </div>
      </div>

      <div
        v-if="expandedIndices.includes(index)"
        class="progress-list-detail"
      >
        <div>
          <span>项目阶段：</span>{{ item.maturity }}
        </div>
        <div>
          <span>形象进度：</span>{{ item.workProcess }}
        </div>
        <div>
          <span>形象进度描述：</span
          >{{ item.processDescription }}
        </div>
        <div>
          <span>是否存在问题：</span>{{ item.problemFlag }}
        </div>
        <div>
          <span>问题描述：</span>{{ item.problemContent }}
        </div>
        <div>
          <span>解决措施：</span>{{ item.solveAdvice }}
        </div>
        <div class="progress-info-item">
          <span class="label">进度图片：</span>
          <span class="value">
            <span v-if="itemImageLists[index].length > 0">
              (共{{ itemImageLists[index].length }}张)
            </span>
            <div
              v-if="itemImageLists[index].length > 0"
              class="image-grid"
            >
              <div
                v-for="(img, imgIndex) in itemImageLists[
                  index
                ]"
                :key="imgIndex"
                class="image-item"
              >
                <el-image
                  :src="getImageUrl(img)"
                  :preview-src-list="
                    getPreviewList(itemImageLists[index])
                  "
                  fit="cover"
                  :initial-index="imgIndex"
                  @error="handleImageError"
                >
                  <div slot="error" class="image-error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  props: {
    dataList: Array,
    isDetail: Boolean,
    stage: String
  },
  watch: {
    dataList: {
      handler(newList, oldList) {
        this.$nextTick(() => {
          this.$forceUpdate()
          // 强制重新计算图片列表
          this.updateImageLists()
        })
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      expandedIndices: [0],
      STATIC_FILE_URL
    }
  },
  computed: {
    // 为每个 item 创建响应式的图片列表
    itemImageLists() {
      return this.dataList.map((item, index) => {
        const images = []
        const processedPaths = new Set()

        // 优先处理 progressImages 中的图片（编辑时使用）
        if (
          item.progressImages &&
          Array.isArray(item.progressImages)
        ) {
          item.progressImages.forEach((img) => {
            if (
              img.filePath &&
              !processedPaths.has(img.filePath)
            ) {
              processedPaths.add(img.filePath)
              images.push(img)
            } else if (img instanceof File || img.raw) {
              images.push(img)
            } else if (img.url) {
              images.push(img)
            }
          })
        }

        // 只有在查询时（没有 progressImages 字段）才使用 resourceFileInfos
        if (
          images.length === 0 &&
          !item.hasOwnProperty('progressImages') &&
          item.resourceFileInfos &&
          Array.isArray(item.resourceFileInfos)
        ) {
          item.resourceFileInfos.forEach((img) => {
            if (
              img.filePath &&
              !processedPaths.has(img.filePath)
            ) {
              processedPaths.add(img.filePath)
              images.push(img)
            }
          })
        }

        return images
      })
    }
  },
  methods: {
    // 强制更新图片列表
    updateImageLists() {
      // 强制重新计算计算属性
      this.$forceUpdate()

      // 强制重新计算 itemImageLists
      this.$nextTick(() => {
        // 触发计算属性重新计算
        const temp = this.itemImageLists
      })
    },
    toggle(index) {
      const i = this.expandedIndices.indexOf(index)
      if (i > -1) {
        this.expandedIndices.splice(i, 1) // 关闭
      } else {
        this.expandedIndices.push(index) // 展开
      }
    },
    deleteProcess(index) {
      this.$confirm('确认删除该条进度信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('delete', index)
      })
    },
    editProcess(item, index) {
      this.$emit('edit', item, index)
    },
    getImageUrl(img) {
      // 处理已上传的图片（有 filePath）
      if (img.filePath) {
        return `${STATIC_FILE_URL}${img.filePath}`
      }
      // 处理新上传的图片（有 url）
      if (img.url) {
        return img.url
      }
      // 处理原始数据
      if (img.originalData) {
        if (img.originalData.filePath) {
          return `${STATIC_FILE_URL}${img.originalData.filePath}`
        }
        if (img.originalData.url) {
          return img.originalData.url
        }
        if (img.originalData instanceof File) {
          return URL.createObjectURL(img.originalData)
        }
      }
      return ''
    },
    getPreviewList(images) {
      return images
        .map((img) => this.getImageUrl(img))
        .filter(Boolean)
    },
    handleImageError(event) {
      // event.target.src = require('@/assets/images/default-image.png')
    }
  }
}
</script>

<style lang="scss" scoped>
.progress-list {
  padding: 10px 10px 0 10px;
  color: #606266;
  height: calc(100% - 50px);
  overflow: auto;

  .progress-list-item {
    margin-bottom: 10px;
  }

  &-time {
    padding: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;

    i {
      margin-right: 6px;
      font-size: 16px;
      transition: color 0.3s;
    }

    .time-text {
      transition: color 0.3s;
    }

    &.active .time-text {
      color: #1890ff;
    }

    .edit {
      color: #1890ff;
      margin-right: 10px;
      cursor: pointer;
    }

    .delete {
      color: red;
      cursor: pointer;
    }
  }

  .progress-list-detail {
    padding-left: 22px;
    div {
      margin-top: 10px;

      span {
        color: #1f1f1f;
        font-weight: 500;
      }
    }

    .progress-info-item {
      margin-top: 10px;

      .label {
        color: #1f1f1f;
        font-weight: 500;
      }

      .value {
        margin-left: 10px;
      }

      .image-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 10px;
      }

      .image-item {
        width: 100px;
        height: 100px;
        border-radius: 4px;
        overflow: hidden;

        .el-image {
          width: 100%;
          height: 100%;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            transform: scale(1.02);
          }
        }
      }

      .image-error {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
        font-size: 30px;
      }
    }
  }
}
</style>
